package com.whfc.ms.api.quality.service.impl;

import com.sargeraswang.util.ExcelUtil.ExcelLogs;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.generator.KeyGeneratorUtil;
import com.whfc.common.result.ResultEnum;
import com.whfc.ms.api.quality.service.MsQualityPartService;
import com.whfc.quality.dto.QualityPartDTO;
import com.whfc.quality.dto.QualityPartImportDTO;
import com.whfc.quality.dto.QualityPartImportResultDTO;
import com.whfc.quality.param.QualityPartAddParam;
import com.whfc.quality.param.QualityPartEditParam;
import com.whfc.quality.service.QualityPartService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author : qzexing
 * @version : 1.0
 * @date : 2020-07-30 15:47
 */
@Service
public class MsQualityPartServiceImpl implements MsQualityPartService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = QualityPartService.class, version = "1.0.0", timeout = 5000)
    private QualityPartService qualityPartService;

    /**
     * 导出excel路径
     */
    private String partExportOssDir = "quality/part/excel";

    @Autowired
    private FileHandler fileHandler;

    @Autowired
    private FilePathConfig filePathConfig;

    @Override
    public List<QualityPartDTO> list(Integer deptId, String keyword) {
        return qualityPartService.list(deptId, keyword);
    }

    @Override
    public void add(QualityPartAddParam request) {
        qualityPartService.add(request);
    }

    @Override
    public void edit(QualityPartEditParam request) {
        qualityPartService.edit(request);
    }

    @Override
    public void del(Integer partId) {
        qualityPartService.del(partId);
    }

    @Override
    public QualityPartImportResultDTO importExcel(Integer deptId, MultipartFile file) {
        //读取excel中的数据
        try {
            Collection<QualityPartImportDTO> data = ExcelUtil.importExcel(QualityPartImportDTO.class,
                    file.getInputStream(), null, new ExcelLogs(), 1);
            if (data == null || data.size() <= 1) {
                //如果只有一行的话则是只有标题
                return new QualityPartImportResultDTO();
            }
            List<QualityPartImportDTO> list = new ArrayList<>(data);
            //去掉标题
            list = list.subList(1, list.size());
            QualityPartImportResultDTO resultDTO = qualityPartService.importPart(deptId, list);
            String path = exportResult(resultDTO.getImportResultList());
            resultDTO.setImportResultDir(path);
            resultDTO.setImportResultList(null);
            return resultDTO;
        } catch (IOException e) {
            logger.warn("导入质量部位失败.", e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "导入质量部位失败.");
        }

    }

    private String exportResult(List<QualityPartImportDTO> importResultList) throws IOException {
        // 将批量导入结果输出到Excel
        String fileName = KeyGeneratorUtil.genStrId() + ".xls";
        File tempFile = File.createTempFile(fileName, "xls");
        tempFile.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(tempFile);
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("code", "编码");
        headers.put("name", "部位名称");
        headers.put("result", "导入结果");
        ExcelUtil.exportExcel(headers, importResultList, fout, "yyyy-MM-dd HH:mm:ss");
        //上传文件到阿里云
        String ossKey = filePathConfig.getFilePath(partExportOssDir, fileName);
        return fileHandler.upload(ossKey, new FileInputStream(tempFile));
    }
}
